package org.fujene.diskblock.local;

import java.io.File;
import java.io.FileInputStream;

import org.fujene.constants.Constants;
import org.fujene.diskblock.DiskBlock;
import org.fujene.memoryblock.MemoryBlock;
import org.fujene.memoryblock.local.LocalInvertIndexBlock;
import org.fujene.structure.LookupPointer;

/**
 * InvertIndexBlockのサブセットとして機能します。
 * 相対ポインタに対応しています。
 */
public class InvertIndexDiskBlock extends DiskBlock{
	public InvertIndexDiskBlock(File fileDesc) throws Exception{
		super(fileDesc);
	}

	public InvertIndexDiskBlock(int ID, File fileDesc, int defaultBodySize, int defaultOptionSize){
		super(ID, fileDesc, Constants.MEMORY_TYPE_INVINDEX, defaultBodySize, defaultOptionSize);
	}

	public InvertIndexDiskBlock(LocalInvertIndexBlock memBlock, String dir){
		super(memBlock, dir);
	}

	public LookupPointer[] getInvertIndex(int ptr) throws Exception{
		if (ptr >= bodySize) return null;

		FileInputStream stream = null;
		byte[] val = new byte[RELPTR];
		LookupPointer[] output = new LookupPointer[2];
		try{
			stream = new FileInputStream(fileDesc);
			switch(version){
			case Constants.FINALVER:
				stream.skip((4 * HEADERLEN) + (4 * optionSize) + ptr);
				stream.read(val);
				output[0] = LookupPointer.fromBytesShort(val);
				if (output[0].equals(LookupPointer.EMPTY_RELATIVE)){
					output[0] = null;
				}else{
					output[0].block += this.getID();
				}
				stream.read(val);
				output[1] = LookupPointer.fromBytesShort(val);
				output[1].block += this.getID();
				break;

			default:
				break;
			}
		}
		finally{
			if (stream != null) stream.close();
		}

		return output;
	}

	@Override
	public int toMemory(MemoryBlock memBlock){
		if (memBlock instanceof LocalInvertIndexBlock){
			try{
				memBlock.setOption(0, this.getOption(0));
				memBlock.setBody(this.getBody(0, this.bodySize), 0);
				memBlock.setBodyVacancy(this.bodyVacancy);
			}
			catch(Exception e){}
		}
		return this.bodySize - this.bodyVacancy;
	}

	@Override
	public byte[] getData(){
		throw new NoSuchMethodError("Unimplemented method");
	}
}
